<?php

namespace Admin\Controller;

class NoticeController extends CommonController
{
    // 公告列表
    public function lists()
    {
        $map  = array();
        $sort = 'sort DESC,id DESC';
        $cut  = 100;

        $key   = I('request.key', '', 'trim');
        $settr = I('request.settr', '', 'intval');

        if ($key) {
            $key_type = I('request.key_type', 0, 'intval');
            if ($key_type == '1') {
                $map['title'] = array('like', '%' . $key . '%');
            }
            if ($key_type == '2') {
                $map['content'] = array('like', '%' . $key . '%');
            }
        }
        if ($settr > 0) {
            $stime          = strtotime("-" . $settr . " day");
            $map['addtime'] = array('GT', $stime);
        }

        $list = D("Notice")->get_list($map, true, $sort, 10, $cut, true);

        $this->assign('notice', $list);

        $this->display();
    }

    // 添加公告
    public function add()
    {
        if (IS_POST) {
            $notice = D("Notice");
            if (!$notice->create()) {
                $this->error($notice->getError());
            } else {
                $notice->uid = session('ytata.uid');
                $notice->add();
                $this->success('保存完成');
            }
        } else {
            $this->display();
        }
    }

    // 编辑公告
    public function edit()
    {
        if (IS_POST) {
            $notice = D("Notice");
            if (!$notice->create()) {
                $this->error($notice->getError());
            } else {
                $notice->save();
                $this->success('保存完成');
            }
        } else {
            $id = I('get.id', '', 'intval');
            if ($id) {
                $notice    = M("Notice");
                $map['id'] = $id;
                $show      = $notice->where($map)->limit(1)->find();
                $this->assign('show', $show);
                $this->display();
            } else {
                $this->error('非法请求');
            }
        }
    }

    // 删除公告
    public function delete()
    {
        $ids = I('request.id');
        $ids = is_array($ids) ? implode(",", $ids) : $ids;
        if ($ids && preg_match("/^(\d{1,10},)*(\d{1,10})$/", $ids)) {
            $s = M("Notice")->delete($ids);
            $this->success("成功删除{$s}条数据");
        } else {
            $this->error('请选择要删除的信息！');
        }
    }
}